<?php

class Application_Model_UserMapper  extends Application_Model_AbstractMapper{

	protected $_dbTableName = "user"; //used in AbstractMapper for Zend_Db_Table_Abstract

	/**
	 * @param  Zend_Db_Table_Row_Abstract $row
	 * @return Application_Model_User
	 */
	protected function _convertToModel($row) {
		$model = new Application_Model_User();
		$model->setId($row['id'])->setUsername($row['username'])->setPassword($row['password'])->setRealName($row['realName']);
	return $model;
	}

	/**
	 * @param Application_Model_User $user
	 */
	public function save(Application_Model_User $user) {
		$data = array('username' => $user->getUsername(), 'password' => $user->getPassword(),
			'realName' => $user->getRealName(),);

		if (null === ($userId = $user->getId())) {
			unset($data['userId']);
			$this->getDbTable()->insert($data);
		} else {
			$this->getDbTable()->update($data, array('userId = ?' => $userId));
		}
	}

	/**
	 * @param	int			$userId
	 * @return Application_Model_User
	 * @throws Exception
	 */
	public function find($userId ) {
		/* ging hier nicht als Parm
		$select = $this->getDbTable()->select()->where('id = ?', $userId);
		$where = $this->getDbTable()->getAdapter()->quoteInto('id = ?', $userId);
		*/
        if (is_int($userId+0)==false) {
			throw new Exception('Applikationsfehler - DB-Key User nicht Integer');
		}

		$result = $this->getDbTable()->find($userId);
		if (0 == count($result)) {
			throw new Exception('Applikationsfehler - DB-Key User nicht verhanden');
		}
		$user = $this->_convertToModel($result->current());
        return $user;
	}

	/**
	 * 	@return Application_Model_User[]
	 */
	public function fetchAll() {
		$resultSet = $this->getDbTable()->fetchAll();
		return $this->_convertToModelArray($resultSet);
	}
}
